<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        class="search-input"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText"></search-result>
    <!-- 搜索建议 -->
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch"></search-suggestion>
    <!-- 搜索历史 -->
    <search-history v-else :search-histories="searchHistories"  @search="onSearch" @clear-search-histories="searchHistories = []"></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { getItem, setItem } from '@/utils/storage'

export default {
  name: 'SearchIndex',
  props: {},
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '', // 输入内容
      isResultShow: false, // 是否结果显示
      searchHistories: getItem('search-histories') || []
    }
  },
  created () {

  },
  methods: {
    onSearch (val) {
      // console.log('onSearch', val)
      this.searchText = val
      this.isResultShow = true
      // 如果存在内容,把移除,再添加
      const index = this.searchHistories.findIndex(t => t === val)
      if (index > -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
    },
    onCancel () {
      // console.log('onCancel')
      this.$router.back()
    }
  },
  watch: {
    searchHistories (val) {
      // console.log('searchHistories', val)
      setItem('search-histories', val)
    }
  }
}
</script>

<style lang="less" scoped>
.van-search__action {
  color: #fff;
}
.search-container{
  padding-top: 108px;
}
.search-input{
  position: fixed;
  top:0px;
  width:100%;
  z-index: 1;
}
</style>
